package com.zhidisoft.crm.controller.auth;


import java.util.UUID;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.zhidisoft.crm.entity.SysRole;
import com.zhidisoft.crm.service.ISysRoleService;
import com.zhidisoft.crm.vo.AjaxVo;

@Controller
@RequestMapping("/auth/role")
public class RoleController {
	
	@Autowired
	ISysRoleService roleService;
	/**
	 * 分页显示角色信息
	 * @param pageNum
	 * @param pageSize
	 * @return
	 */
	@GetMapping("/list")
	public ModelAndView list(@RequestParam(name = "pageNum", defaultValue = "1") Integer pageNum,
			@RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
		ModelAndView modelAndView=new ModelAndView("auth/role/list.html");
		modelAndView.addObject("list", roleService.findPage(pageNum, pageSize));
		modelAndView.addObject("totalCount", roleService.totalCount());
		return modelAndView;  // 省代码(视图解析器)
	}
	/**
	 * 跳转到添加页面
	 * @return
	 */
	@GetMapping("/save")
	public String save(){
		return "auth/role/addrole.html";
	}
	/**
	 * 跳转到修改页面
	 * @param id
	 * @return
	 */
	@GetMapping("/update/{role_id}")
	public ModelAndView update(@PathVariable(name="role_id")String role_id){
		SysRole role = roleService.selectById(role_id);
		return new ModelAndView("auth/role/updaterole.html","role",role);
	}
	/**
	 * 添加角色
	 * @param sysRole
	 */
	@PostMapping("/save")
	@ResponseBody
	public AjaxVo saverole(@Valid SysRole sysRole, BindingResult result){
		if (result.hasErrors()) {
			for (ObjectError error : result.getAllErrors()) {
				return new AjaxVo().setErrorCode("10002").setErrorMsg(error.getDefaultMessage());
			}
		}
		sysRole.setId(UUID.randomUUID().toString().replace("-", ""));
		roleService.save(sysRole);
		return new AjaxVo().setErrorCode("0");
	}
	/**
	 * 根据id修改角色
	 * @param sysRole
	 * @param id
	 */
	@PostMapping("/update/{id}")
	@ResponseBody
	public void updateRole(@Valid SysRole sysRole, @PathVariable("id")String id){
		sysRole.setId(id);
		roleService.update(sysRole);
	}
	/**
	 * 根据id删除角色
	 * @param id
	 */
	@DeleteMapping("/delete/{id}")
	@ResponseBody
	public void delete(@PathVariable("id") String id) {
		roleService.deleteById(id);
	}
	
	
}
